import * as Koa from 'koa';
import { getMenus } from "../entity/menu";
import { getRoles } from '../entity/role';

const errorMsg = `服务器错误：${'menu'}`;
const successMsg = `成功：${'menu'}`;

export default class MenuService {
  getOneLevelMenusList = async (ctx: Koa.Context) => {
    try {
      const result: any = await getMenus(ctx);
      result.data = result.data.filter(item => !item.pid).map((item: any) => ({
        label: item.title,
        value: item.id + "",
      }));
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(result.data || [], successMsg);
      }
    } catch (error) {
      ctx.fail(null, error, -1);
    }
  };
  
  getMenus = async (ctx: Koa.Context) => {
    try {
      let { roleId } = ctx.request.body;
      let roleResult: any = {};
      if (roleId) {
        roleResult = await getRoles(ctx, { condition: ` where rid = "${roleId}"` }, { needRoleName: false });
      } else {
        // 默认权限ID默认“普通用户”
        roleResult = await getRoles(ctx, { condition: ` where is_default = "1"` }, { needRoleName: false });
      }

      const result: any = await getMenus(ctx);

      
      // 获取指定权限的菜单
      if (roleResult.data?.[0]?.menuIds) {
        const arr = roleResult.data[0].menuIds.split(',');
        result.data = result.data.filter(item => {
          if (item.pid) {
            const _id =  result.data.find(parentItem => parentItem.mid === item.pid)?.id;
            return arr.includes(_id + "");
          } else {
            return arr.includes(item.id + "");
          }
        });
      }
      
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(result.data || [], successMsg);
      }
    } catch (error) {
      ctx.fail(null, error, -1);
    }
  };
}
